package com.lixinlei.meetingfilm.consumer.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ConsumerServiceImpl implements ConsumerServiceAPI {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public String sayHello(String message) {

//        return method1(message);
//        return method2(message);
        return method3(message);

    }

    /**
     * 硬编码 host 和 port，@LoadBalanced 就不能加在 RestTemplate 上；
     * @param message
     * @return
     */
    private String method1(String message) {
        String hostname = "127.0.0.1";
        int port = 7101;

        String uri = "/provider/sayhello?message=" + message;
        String url = "http://" + hostname + ":" + port + uri;

        // http://localhost:7101/provider/sayhello?message=hello
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    /**
     * 从 Eureka 中获得 host 和 port，并且是带负载均衡的；
     * @param message
     * @return
     */
    private String method2(String message) {
        ServiceInstance choose = loadBalancerClient.choose("hello-service-provider");
        String hostname = choose.getHost();
        int port = choose.getPort();

        String uri = "/provider/sayhello?message=" + message;
        String url = "http://" + hostname + ":" + port + uri;

        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    /**
     * @LoadBalanced 加在 RestTemplate 上，url 就可以直接用 service-name 了；
     * @param message
     * @return
     */
    private String method3(String message) {
        String uri = "/provider/sayhello?message=" + message;
        String url = "http://hello-service-provider" + uri;

        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

}
